package org.comet.auxiliary.client.liaobei.util;

import org.apache.http.client.config.RequestConfig;
import org.comet.auxiliary.common.util.*;
import org.comet.auxiliary.common.util.crypto.MD5Util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wq
 * @date 2019/12/5
 * @description lapu-palm-client
 */
public class LapuUtil {

    private static long currentTime = 0L;

    public static Map<String, Object> validKey(String host, String product, int port, String url0, String key) {
        String reqUrl = "http://" + host + ":" + port + url0 + "/thunder/activation/checkKey";
        String params = "key=" + key + "&product=" + product + "&machineId=" + MachineUtil.getCpuId();
        String result = HttpUtils.httpClientGet(reqUrl, null, params);
        if (!StringUtil.isBlank(result)) {
            Map<String, Object> res = JsonUtils.getMap(result);
            int code = Integer.parseInt(res.get("code").toString());
            if (code == 2000) {
                return (Map<String, Object>) res.get("data");
            }
        }
        // 0.正常 1.异常 2.被封 3.过期 4.产品错位 5.机器错位
        return null;
    }

    public static Map<String, Object> login(String phone, String code) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("appId", "org.yxdomainname.cailiao111");
        params.put("xmppVersion", "1");
        params.put("loginType", "0");
        params.put("areaCode", "86");
        params.put("grant_type", "client_credentials");
        params.put("latitude", "123.17720078578824");
        params.put("longitude", "123.3476694405959");
        params.put("serial", "R2B06F16343C4EE2BFFE750AD8EBE3E4");
        params.put("telephone", MD5Util.getMD5(phone));
        params.put("password", MD5Util.getMD5(code));
        params.put("secret", MD5Util.getMD5(time));
        params.put("time", time);

        String res = post("user/login", params);
        Map<String, Object> result = JsonUtils.getMap(res);
        System.out.println(result.toString());
        Object status = result.get("resultCode");
        if (status != null && "1".equals(status.toString())) {
            String currentTime0 = result.getOrDefault("currentTime", "0").toString();
            currentTime = Long.parseLong(currentTime0);
            currentTime -= System.currentTimeMillis();;
            return (Map<String, Object>) result.get("data");
        } else {
            System.out.println("== login error == :: " + res);
        }
        return null;
    }

    private static String getTime() {
        return (System.currentTimeMillis() + currentTime) / 1000L + "";
    }

    public static String post(String url, Map<String, String> params) throws Exception {
        return post(url, params, 7000);
    }

    public static String post(String url, Map<String, String> params, int socketTimeout) throws Exception {
        Map<String, String> heads = new HashMap<>(8);
        heads.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3100)
                .setSocketTimeout(socketTimeout)
                .setCookieSpec("mySpec")
                .build();

        return HttpUtils.httpClientPost("http://47.52.153.185:8092/" + url, heads, params, requestConfig);
    }

    /**
     * 查询通讯录
     */
    public static Map<String, Object> queryFriendList(String tk, String uid) throws Exception {
        Map<String, Object> data = new HashMap<>(2);
        data.put("friend", queryFriend(tk, uid));
        data.put("group", queryGroup(tk, uid));
        return data;
    }

    public static List<Map<String, Object>> queryFriend(String tk, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("time", time);
        params.put("userId", uid);
        String md5 = MD5Util.getMD5(time + uid + tk);
        params.put("secret", md5);
        System.out.println("== secret: " + md5);

        String res = post("friends/attention/list?pageIndex=0&pageSize=1200", params);
        Map<String, Object> result = JsonUtils.getMap(res);
        Object status = result.get("resultCode");
        if (status != null && "1".equals(status.toString())) {
            Object data = result.get("data");
            if (data instanceof List) {
                return (List<Map<String, Object>>) data;
            } else {
                ArrayList<Map<String, Object>> list = new ArrayList<>();
                if (data != null) {
                    list.add((Map<String, Object>) data);
                }
                return list;
            }
        } else {
            System.out.println("== queryFriend error == :: " + res);
        }
        return null;
    }

    public static List<Map<String, Object>> queryGroup(String tk, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("time", time);
        params.put("userId", uid);
        params.put("secret", MD5Util.getMD5(time + uid + tk));

        String res = post("room/list/his?pageSize=1000&pageIndex=0", params);
        Map<String, Object> result = JsonUtils.getMap(res);
        Object status = result.get("resultCode");
        if (status != null && "1".equals(status.toString())) {
            Object data = result.get("data");
            if (data instanceof List) {
                return (List<Map<String, Object>>) data;
            } else {
                ArrayList<Map<String, Object>> list = new ArrayList<>();
                if (data != null) {
                    list.add((Map<String, Object>) data);
                }
                return list;
            }
        } else {
            System.out.println("== queryGroup error == :: " + res);
        }
        return null;
    }

    /**
     * 查余额
     */
    public static String queryBalance(String tk, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("time", time);
        String secret = MD5Util.getMD5(
                time +
                        uid +
                        tk
        );
        params.put("secret", secret);

        String res = post("user/getUserMoeny", params);
        Map<String, Object> result = JsonUtils.getMap(res);
        Object status = result.get("resultCode");
        if (status != null && "1".equals(status.toString())) {
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            if (data != null) {
                return data.getOrDefault("balance", "").toString();
            }
        } else {
            System.out.println("== queryBalance error == :: " + res);
        }
        return "";
    }

    /**
     * 领红包
     */
    public static String takePacket(String tk, String uid, String tno) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("time", time);
        params.put("id", tno);
        String secret = MD5Util.getMD5(
                MD5Util.getMD5(time) +
                        uid +
                        tk
        );
        params.put("secret", secret);
        return post("redPacket/openRedPacket", params);
    }

    public static int queryPacketMoney(String tk, String packetId, String uid) throws Exception {
        String res = queryPacket(tk, packetId, uid);
        Map<String, Object> result = JsonUtils.getMap(res);
        if ("1".equals(result.getOrDefault("resultCode", "0").toString())) {
            result = (Map<String, Object>) result.get("data");
            result = (Map<String, Object>) result.get("packet");
            String giftMoney = result.get("money").toString();
            return new BigDecimal(giftMoney).multiply(BigDecimal.valueOf(100d)).intValue();
        }
        return 0;
    }

    /**
     * 查询红包情况
     */
    public static String queryPacket(String tk, String packetId, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("time", time);
        params.put("id", packetId);
        String secret = MD5Util.getMD5(
                time +
                        uid +
                        tk
        );
        params.put("secret", secret);

        return post("redPacket/getRedPacket", params);
    }


    /**
     * 发包
     */
    public static String sendPacket(String tk, String pwd, String uid, String toId, Integer amt, String title) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        String moneyStr = MathUtil.getYuanFromFen(amt) + "";
        params.put("moneyStr", moneyStr);
        params.put("access_token", tk);
        params.put("count", "1");
        params.put("greetings", title);
        params.put("type", "1");
        params.put("time", time);
        params.put("toUserId", toId);
        String secret = MD5Util.getMD5(
                MD5Util.getMD5(time + moneyStr) +
                        uid +
                        tk +
                        MD5Util.getMD5(pwd)
        );
        params.put("secret", secret);

        return post("redPacket/sendRedPacket/v1", params);
    }

    /**
     * 发群包
     */
    public static String sendRelationPacket(String tk, String pwd, Integer packetAmt, Integer count, String rid, String packetText, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        String moneyStr = MathUtil.getYuanFromFen(packetAmt) + "";
        params.put("moneyStr", moneyStr);
        params.put("access_token", tk);
        params.put("count", count+"");
        params.put("greetings", packetText);
        params.put("type", "2");
        params.put("time", time);
        params.put("roomJid", rid);
        String secret = MD5Util.getMD5(
                MD5Util.getMD5(time + moneyStr) +
                        uid +
                        tk +
                        MD5Util.getMD5(pwd)
        );
        params.put("secret", secret);
        return post("redPacket/sendRedPacket/v1", params);
    }

    /**
     * 转账
     */
    public static String transAccount(String tk, String pwd, Integer packetAmt, String toId, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        String moneyStr = MathUtil.getYuanFromFen(packetAmt) + "";
        params.put("access_token", tk);
        params.put("money", moneyStr);
        params.put("remark", "auto");
        params.put("time", time);
        params.put("toUserId", toId);
        String secret = MD5Util.getMD5(
                MD5Util.getMD5(time + moneyStr) +
                        uid +
                        tk +
                        MD5Util.getMD5(pwd)
        );
        params.put("secret", secret);
        return post("skTransfer/sendTransfer", params);
    }

    public static String queryMemberList(String rid, String tk, String uid) throws Exception {
        Map<String, String> params = new HashMap<>(16);
        String time = getTime();
        params.put("access_token", tk);
        params.put("roomId", rid);
        params.put("time", time);
        String secret = MD5Util.getMD5(
                time +
                        uid +
                        tk
        );
        params.put("secret", secret);
        return post("room/get", params);
    }
}
